package chabernac.gravidroid.model;

public class Line {
    // AX + BY + C = 0
    // 1x + 1y + 0 = 0
    // y = -x;
    // y = x;
    // y-x = 0
    // -1x + 1y = 0
    // y = 2x;
    // -2x + 1y

    public float A;
    public float B;
    public float C;
    
    private Vector p1;
    private Vector p2;
    private Vector p1top2 = new Vector();

    public Line( float A, float B, float C ) {
        this.A = A;
        this.B = B;
        this.C = C;
    }

    public Line( Vector aP1, Vector aP2 ) {
        p1 = aP1;
        p2 = aP2;
    }
    
    public void recalculate(){
        p1top2.set( p2.x - p1.x, p2.y - p1.y );
        p1top2.normalize( p1top2 );
        A = -p1top2.y;
        B = p1top2.x;
        C = -( A * p1.x + B * p1.y );
    }

    public float distanceToPoint( Vector aVector ) {
        return A * aVector.x + B * aVector.y + C;
    }

    public Vector getRico() {
        return new Vector( B, -A );
    }

    public Line getOrthogonalLineThroughPoint( Vector aPoint ) {
        return Line.constructFromRicoAndPoint( new Vector( A, B ), aPoint );
    }

    /*
     * L1 <-> Ax + By + C = 0; L2 <-> A'x + B'y + C' = 0
     */
    public Vector intersect( Line aL ) {
        float det = A * aL.B - aL.A * B;
        if ( det == 0 ) {
            return null;
        } else {
            float x = ( B * aL.C - aL.B * C ) / det;
            float y = ( aL.A * C - A * aL.C ) / det;
            return new Vector( x, y );
        }
    }

    public static Line constructFromTwoPoints( Vector aP1, Vector aP2 ) {
        Vector theRico = new Vector( aP1, aP2 );
        theRico.normalize( theRico );
        float A = -theRico.y;
        float B = theRico.x;
        float C = -( A * aP1.x + B * aP1.y );
        return new Line( A, B, C );
    }

    public static Line constructFromRicoAndPoint( Vector aRico, Vector aPoint ) {
        float A = -aRico.y;
        float B = aRico.x;
        float C = -( A * aPoint.x + B * aPoint.y );
        return new Line( A, B, C );
    }

    public static void main( String args[] ) {
        Line theLine = new Line( new Vector( 0, 0 ), new Vector( 1, 1 ) );
        System.out.println( theLine.distanceToPoint( new Vector( 4, 4 ) ) );
    }
}
